<template>
    <div class="l-rule">
        <el-button-group class="l-rule-button">
            <el-button size="mini" type="primary" @click="createRule()">新建权限</el-button>
            <el-button size="mini" type="danger" @click="batchDel()">删除权限</el-button>
        </el-button-group>
        <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column type="index" width="50">
            </el-table-column>
            <el-table-column prop="rule_title" label="权限标题">
            </el-table-column>
            <el-table-column prop="rule_name" label="权限名称">
            </el-table-column>
            <el-table-column prop="model_title" label="模板标题">
            </el-table-column>
            <el-table-column prop="model_name" label="模板名称">
            </el-table-column>
            <el-table-column prop="rule_status" label="状态">
                <template slot-scope="scope">
                    <el-switch v-model="scope.row.rule_status" active-color="#409eff" inactive-color="#dfdfdf" :active-value="1" :inactive-value="2" @change="handlerState(scope.row)" />
                </template>
            </el-table-column>
            <el-table-column prop="action" label="操作" width="180">
                <template slot-scope="scope">
                    <el-button size="small" type="" @click="setUpdate(scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="intDel(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination :page-size="page.size" :current-page="page.page" :pager-count="7" layout="prev, pager, next" :total="page.total" @current-change="handlerPage">
        </el-pagination>
        <el-dialog :title="dialog.title" :visible.sync="dialogVisible" :close-on-click-modal="false" class="dislog-rule" width="600px">
            <div>
                <el-row type="flex">
                    <el-col :span="6" class="j-rule-label">权限标题：</el-col>
                    <el-col :span="18">
                        <el-input style="width:350px;" v-model="rule.rule_title" placeholder="请填入权限标题" />
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="6" class="j-rule-label">权限名称：</el-col>
                    <el-col :span="18">
                        <el-input style="width:350px;" v-model="rule.rule_name" placeholder="请填入权限名称" />
                        <p class="j-rule-tips">*提示：名称只可用字母、数字组成。例：checkOrder(查看订单)</p>
                    </el-col>
                </el-row>
                <el-row type="flex">
                    <el-col :span="6" class="j-rule-label">模块标题：</el-col>
                    <el-col :span="18">
                        <el-select v-model="rule.model_name" clearable placeholder="请选择模块" @change="handlerModel()">
                            <el-option v-for="item in models" :key="item.name" :label="item.title" :value="item.name">
                            </el-option>
                        </el-select>
                    </el-col>
                </el-row>
                <el-row type="flex">
                    <el-col :span="6" class="j-rule-label">权限状态：</el-col>
                    <el-col :span="18">
                        <el-radio-group v-model="rule.rule_status">
                            <el-radio :label="1">显示</el-radio>
                            <el-radio :label="2">隐藏</el-radio>
                        </el-radio-group>
                    </el-col>
                </el-row>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" v-if="dialog.cancel" @click="dialogVisible = false">{{dialog.cancel}}</el-button>
                <el-button size="small" type="primary" @click="intAction()">{{dialog.determine}}</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script type="text/javascript">
import { get_config_all,get_rule_all,add_rule,edit_rule,del_rule,get_rule_count } from "@/api/rule"
export default {
    components: {
        //empty
    },
    props: {
        value: [Array, Object]
    },
    data() {
        return {
            // 单条权限
            rule: {},
            // 多选权限
            selectionRule:[],

            //查询数据组
            tableData: [],

            //页面状态
            page_state:'add',

            // 模块组
            models: [],

            // 模态框配置
            dialogVisible: false,
            dialog: {
                title: '新增权限',
                determine: '添加',
                cancel: "取消"
            },

            // 分页配置
            page:{
              size:10,
              page:1,
              total:0,
            }

        }
    },
    /**
     * 计算属性
     * @type {Object}
     */
    computed: {

    },
    /**
     * 数据监听
     * @type {Object}
     */
    watch: {

    },
    /**
     * 页面加载执行
     * @return {[type]} [description]
     */
    mounted() {
        // 获取模块组
        this.getMobles();
        // 获取全部权限
        this.getRuleAll();
        // 获取页码总数量
        this.getCount();
    },
    /**
     * 页面方法
     * @type {Object}
     */
    methods: {
        // 分页功能
        handlerPage(page){
          this.page.page = page;
          this.getRuleAll();
        },

        // 模态框操作
        intAction() {
          switch(this.page_state){
            case 'add':
              this.addRule();
            break;
            case 'edit':
              this.editRule();
            break;
          }
        },

        // 添加权限
        createRule() {
            this.rule = {};
            this.dialogVisible = true;
            this.page_state = 'add';
            this.dialog = {
                title: "新增权限",
                determine: "添加",
                cancel: "取消",
            }

        },

        // 批量删除权限组
        batchDel() {
            if (this.selectionRule.length > 0) {
              this.intDel(this.selectionRule);
            }else{
              this.$message({
                message: '请选择需要删除的数据！',
                type: 'warning'
              });
            }
        },

        // 编辑权限
        setUpdate(data) {
            this.rule = JSON.parse(JSON.stringify(data));
            this.page_state = 'edit';
            this.dialogVisible = true;
            this.dialog = {
                title: "编辑权限",
                determine: "更新",
                cancel: "取消",
            }

        },

        // 删除权限
        intDel(data) {
            this.rule = JSON.parse(JSON.stringify(data));
            this.$confirm('此操作将永久删除该权限设置, 不可恢复, 是否继续?', '系统提示', {
                confirmButtonText: '继续',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let _id = [];
                if(data.length > 0){
                  data.forEach(item => {
                    _id.push(item._id);
                  })
                }else{
                  _id.push(data._id);
                }
                this.delData({_id:_id});
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },


        /**
         * 检测必填项
         * @return {[type]} [description]
         */
        checkData(){
          var name = /^[A-Za-z0-9]+$/;
          var ret = false;
          var tips= null;
          if(!this.rule.rule_title){
            tips = '请填入权限标题！';
            ret = true;
          }else if(!this.rule.rule_name){
            tips = '请填入权限名称！';
            ret = true;
          }else if(!name.test(this.rule.rule_name)){
              tips = '权限名称不符合规则！';
              ret = true;
          }else if(!this.rule.model_name){
            tips = '请选择所属模块！';
            ret = true;
          }else if(!this.rule.rule_status){
            tips = "请选择权限状态"
            ret = true
          }

          if(ret){
            this.$message({
                message: tips,
                type: 'warning'
              });
            return false;
          }
          return true;
        },

        /**
         * 监听模块发生变化
         * @param  {[type]} item [description]
         * @return {[type]}      [description]
         */
        handlerModel(){
          this.models.forEach(item => {
            if(this.rule.model_name == item.name){
              this.rule.model_title = item.title
            }
          })
        },

        /**
         * 多选数据
         * @return {[type]} [description]
         */
        handleSelectionChange(data){
          this.selectionRule = data;
        },



        /*************************   数据处理   ****************************/
        /**
         * 获取权限总条数
         * @return {[type]} [description]
         */
        getCount(){
          get_rule_count().then(response => {
            this.page.total = response;
          })
        },

        /**
         * 获取模块组
         * @return {[type]} [description]
         */
        getMobles(){
          get_config_all().then(response => {
            this.models = response;
          })
        },

        /**
         *  获取所有权限
         * @return {[type]} [description]
         */
        getRuleAll(){
          get_rule_all(this.page).then(response => {
            this.tableData = response;
          })
        },


        /**
         * 添加权限 - API
         */
        addRule(){
          if( !this.checkData() ){ return false }
          add_rule(this.rule).then(response => { 
              this.$message({
                message: '添加权限成功！',
                type: 'success'
              });
              this.dialogVisible = false;
              this.getRuleAll();
          })
        },

        /**
         * 更新权限
         * @return {[type]} [description]
         */
        editRule(){
          if( !this.checkData() ){ return false}
          edit_rule(this.rule).then(response => {
              this.$message({
                message: '更新权限成功！',
                type: 'success'
              });
              this.dialogVisible = false;
              this.getRuleAll();
          })
        },

        // 删除权限
        delData(data){
          del_rule(data).then(response => {
              this.$message({
                message: '删除权限成功！',
                type: 'success'
              });
              this.dialogVisible = false;
              this.getRuleAll();
          })
        },

        // 修改权限状态
        handlerState(data) {
          edit_rule(data).then(response => {
              this.$message({
                message: '更新权限成功！',
                type: 'success'
              });
              this.getRuleAll();
          })
        }, 
    }
}
</script>
<style type="text/css" lang="scss">
.l-rule {
    .l-rule-button {
        margin-bottom: 10px;
    }

    .el-pagination {
        text-align: right;
        margin-top: 8px;
        padding-right: 1px;
    }
}

.el-row--flex {
    align-items: center;
    margin-bottom: 15px;

    &:last-child {
        margin-bottom: 0px;
    }
}

.el-select-dropdown {
    .el-scrollbar:not(.el-menu--collapse) {
        min-height: 0px;
    }
}


.dislog-rule {
    .el-checkbox__label {
        margin-bottom: 15px;
    }

    .j-rule-label {
        text-align: right;
    }

    .j-rule-tips {
      color:red;
      font-size: 12px;
      padding: 0px;
      margin: 0px;
      margin-bottom: 15px;
    }
}
</style>